Xbasic

json_sqlQuery Function

Syntax

json_sqlQuery(json as C,sqlStatement as C[,argsIn as A [, columnTypes as C [, otherOpsIn as A]]])

Arguments

jsonCharacter

The JSON object to query.

sqlStatementCharacter

The SQL statement to execute on the JSON.

argsInsql::arguments

Default null_value(). An optional SQL::Arguments object that defines any arguments used in the SQL query. This property is required if your SQL query uses arguments.

columnTypes Character

Default ""

otherOpsInAny Type

Default null_value()

Description

json_sqlQuery Function allows you to filter a JSON array using a simple SQL query syntax.

Discussion

For example assume you have a JSON string as shown below. The JSON is an array of objects. You can think of this as a table with the following fields: firstname, lastname, city and state.

dim json as c 
json = <<%str%
[
    {"firstname":"John","lastname":"Smith","city":"Boston","state":"MA"},
    {"firstname":"Fred","lastname":"Jones","city":"Cambridge","state":"MA"},
    {"firstname":"Tom","lastname":"King","city":"New York","state":"NY"}
]
%str%

Assume that you want to apply a filter to this string to retrieve certain records and also to sort the result. The SQL that you would need to express your query might be:

select * from JSONTABLE WHERE state = 'MA' ORDER BY lastname

Or if you would like to use arguments in your SQL, you might express your query as:

select * from JSONTABLE WHERE state = :whatstate ORDER BY lastname

Here is how you can use the json_sqlQuery() function:

dim args as sql::arguments 
args.add("whatstate","MA")
dim jsonResult as c 
json2 = json_sqlQuery(json,"select * from jsontable where state = :whatstate ORDER BY lastname",args)

The resulting string will be:

[
    {firstname: 'Fred', lastname: 'Jones', city: 'Cambridge', state: 'MA'},
    {firstname: 'John', lastname: 'Smith', city: 'Boston', state: 'MA'}
]

See Also